package api

import (
	"PublicBenefitActivities/config"
	"PublicBenefitActivities/models"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"
)

func GetWxLoginRes(code string) (*models.WXLoginRes, error) {
	url := fmt.Sprintf(
		"https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
		config.Config.GetString("wechat.appid"),
		config.Config.GetString("wechat.appSercert"),
		code,
	)

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)

	if err != nil {
		return nil, err
	}

	client := http.Client{}

	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	var wxLoginRes models.WXLoginRes
	if err := json.Unmarshal(body, &wxLoginRes); err != nil {
		return nil, err
	}

	if wxLoginRes.ErrCode != 0 {
		return nil, fmt.Errorf("wechat api error: %d - %s", wxLoginRes.ErrCode, wxLoginRes.ErrMsg)
	}

	return &wxLoginRes, nil
}
